package com.javen.bankpay;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.javen.weixin.controller.WeiXinOauthController;
import com.jfinal.core.Controller;
import com.jfinal.log.Log;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;

public class TestPayInterface extends Controller{
	static Log log = Log.getLog(WeiXinOauthController.class);
	
	private static String domain = "https://pay.xjpay.cc";//接口域名
	private static String appId = "10058778";//分配的代理商唯一标识
	private static String key = "2fa9e73d255d4cec88e4f92f5006d204";
	static PayInterfaceService payInterfaceService = new PayInterfaceService();
	public static void main(String[] args) {
		List<Record> debits = Db.find("select * from debit_card");
		for(Record debit : debits){
			log.info(debit.getStr("id_name"));
		}
	}
	
	//结算卡修改和费率修改
	public static void changeFee(){
		String path = "/api/debit";

		String openID = "openID";
		String card_no = "card_no";// 卡号
		String bank_phone = "bank_phone";// 手机号
		
		Record thisDebitCard = payInterfaceService.getDebits(openID).get(0);
		String id_name = thisDebitCard.getStr("id_name");// 姓名
		String id_no = thisDebitCard.getStr("id_no");// 身份证号

		String nonceStr = System.currentTimeMillis() + getRandomString(8);// 随机字符串
		String customerInfo = DesUtil.encode(card_no + "|" + id_name + "|" + id_no + "|" + bank_phone, key);// 用户信息3des加密
		String merchantFlag = "M02";//修改类型(M02:修改结算卡，M03:修改费率）
		String mchId = thisDebitCard.getStr("mchId");//商户号
		String provinceCode = thisDebitCard.getStr("provinceCode");// 省份编码
		String cityCode = thisDebitCard.getStr("cityCode");// 城市编码
		Double fee0 = thisDebitCard.getDouble("fee0");// 费率
		int d0fee = thisDebitCard.getInt("d0fee");// 单笔费用

		// 签名map
		Map<String, String> signParams = new HashMap<String, String>();
		signParams.put("appId", appId);
		signParams.put("nonceStr", nonceStr);
		signParams.put("customerInfo", customerInfo);
		signParams.put("merchantFlag", merchantFlag);
		signParams.put("mchId", mchId);
		signParams.put("provinceCode", provinceCode);
		signParams.put("cityCode", cityCode);
		signParams.put("fee0", fee0.toString());
		signParams.put("d0fee", String.valueOf(d0fee));

		//签名
		String sign = MerchSdkSign.getSign(signParams, key);

		// 请求参数map
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("appId", appId);
		params.put("sign", sign);
		params.put("nonceStr", nonceStr);
		params.put("customerInfo", customerInfo);
		params.put("merchantFlag", merchantFlag);
		params.put("mchId", mchId);
		params.put("provinceCode", provinceCode);
		params.put("cityCode", cityCode);
		params.put("fee0", fee0);
		params.put("d0fee", d0fee);

		log.info(JSONObject.toJSONString(params));
		JSONObject response = JSON.parseObject(sendPut(domain + path, JSONObject.toJSONString(params)));
		log.info("结算卡修改和费率修改同步返回结果：" + response.toJSONString());
		if(response.getString("isSuccess").equals("true")){
			thisDebitCard.set("card_no", card_no);
			thisDebitCard.set("bank_phone", bank_phone);
			payInterfaceService.updateDebitCard(thisDebitCard);
		}else{
			log.info(response.getString("message"));
		}
		
	}
	
	/*
	 * 发送http put请求
	 */
	public static String sendPut(String httpUrl, String params) {  
        String result = "";  
        URL url = null;  
        try {  
            url = new URL(httpUrl);  
        } catch (MalformedURLException e) {  
            e.printStackTrace();  
        }  
        if (url != null) {  
            try {  
                HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();  
                urlConn.setRequestProperty("content-type", "application/json");  
                urlConn.setDoInput(true);  
                urlConn.setDoOutput(true);  
                urlConn.setConnectTimeout(5 * 1000);  
                //设置请求方式为 PUT  
                urlConn.setRequestMethod("PUT");  
                  
                urlConn.setRequestProperty("Content-Type", "application/json");  
                urlConn.setRequestProperty("Accept", "application/json");  
                  
                urlConn.setRequestProperty("Charset", "UTF-8");  
                  
      
                DataOutputStream dos = new DataOutputStream(urlConn.getOutputStream());  
                //写入请求参数  
                //这里要注意的是，在构造JSON字符串的时候，实践证明，最好不要使用单引号，而是用“\”进行转义，否则会报错  
                 // 关于这一点在上面给出的参考文章里面有说明  
                dos.writeBytes(params);  
                dos.flush();  
                dos.close();  
                  
                if (urlConn.getResponseCode() == 200) {  
                    InputStreamReader isr = new InputStreamReader(urlConn.getInputStream());  
                    BufferedReader br = new BufferedReader(isr);  
                    String inputLine = null;  
                    while ((inputLine = br.readLine()) != null) {  
                        result += inputLine;  
                    }  
                    isr.close();  
                    urlConn.disconnect();  
                }  
  
            } catch (Exception e) {  
                e.printStackTrace();  
            }  
        }  
  
        return result;  
  
    }
	
	/*
	 * 生成随机字符串
	 */
	public static String getRandomString(int length) { //length表示生成字符串的长度  
	    String base = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
	    Random random = new Random();     
	    StringBuffer sb = new StringBuffer();     
	    for (int i = 0; i < length; i++) {     
	        int number = random.nextInt(base.length());     
	        sb.append(base.charAt(number));     
	    }     
	    return sb.toString();     
	 }  

}
